from flask import Blueprint, request, jsonify
from db import db1
from math import ceil
import json

bp_fenlei = Blueprint('lianxi', __name__)


# 添加分类
@bp_fenlei.route('/add', methods=['POST'])
def addcate():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    sql = """insert into cate(name) values('%s')""" % (data['name'])
    db1.insert(sql)
    return jsonify({'code': 200})


# 添加商品
@bp_fenlei.route('/addgoods', methods=['POST','GET'])
def addgoods():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    if request.method == 'POST':
        sql = """insert into goods values(0,'%s','%d')""" % (data['name'], int(data['cid']))
        db1.insert(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        cpage = int(request.args.get('cpage'))
        size = 2
        start = (cpage - 1) * size
        sql = """select g.id,g.name,g.cid,c.name from goods as g left join cate as c on g.cid=c.id order by id desc limit %d,%d""" % (
        start, size)
        list = db1.findall(sql)
        sql = """select count(-1) as co  from goods"""
        numm = db1.findall(sql)
        total = ceil(numm[0]['co']/size)
        return jsonify({'code': 200,"list":list,"numm":total})
